package jfconfig;

/**
 * Created : May 17, 2012
 *
 * @author pquiring
 */

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;

import javaforce.*;

public class PrinterJobsDialog extends javax.swing.JDialog {

  /**
   * Creates new form PrinterJobsDialog
   */
  public PrinterJobsDialog(java.awt.Frame parent, boolean modal, String pname) {
    super(parent, modal);
    initComponents();
    setPosition();
    this.pname = pname;
    model = (DefaultTableModel)jobs.getModel();
    listJobs();
    //create a timer to refresh list every 5 secs
    timer = new java.util.Timer();
    timer.schedule(new TimerTask() {
      public void run() {
        java.awt.EventQueue.invokeLater(new Runnable() {public void run() { listJobs(); }});
      }
    }, 5000, 5000);
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    deleteJob = new javax.swing.JButton();
    close = new javax.swing.JButton();
    jScrollPane2 = new javax.swing.JScrollPane();
    jobs = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Jobs");
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        formWindowClosing(evt);
      }
    });

    deleteJob.setText("Delete Job");
    deleteJob.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        deleteJobActionPerformed(evt);
      }
    });

    close.setText("Close");
    close.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        closeActionPerformed(evt);
      }
    });

    jobs.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "Rank", "Owner", "JobID", "Files", "Size"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
      };
      boolean[] canEdit = new boolean [] {
        false, false, false, false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    jobs.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    jScrollPane2.setViewportView(jobs);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jScrollPane2)
          .addGroup(layout.createSequentialGroup()
            .addComponent(deleteJob)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 281, Short.MAX_VALUE)
            .addComponent(close)))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(deleteJob)
          .addComponent(close))
        .addContainerGap())
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeActionPerformed
    dispose();
  }//GEN-LAST:event_closeActionPerformed

  private void deleteJobActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteJobActionPerformed
    deleteJob();
  }//GEN-LAST:event_deleteJobActionPerformed

  private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
    timer.cancel();
  }//GEN-LAST:event_formWindowClosing

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton close;
  private javax.swing.JButton deleteJob;
  private javax.swing.JScrollPane jScrollPane2;
  private javax.swing.JTable jobs;
  // End of variables declaration//GEN-END:variables

  private DefaultTableModel model;
  private String pname;
  private java.util.Timer timer;

  private void listJobs() {
    model.setRowCount(0);
    ShellProcess sp = new ShellProcess();
    String output = sp.run(new String[] {"lpq", "-P", pname}, false);
    String lns[] = output.split("\n");
    if (lns.length < 2) return;
    for(int a=2;a<lns.length;a++) {
      String f[] = lns[a].split(" +", 4);
      if (f.length != 5) continue;
      model.addRow(new Object[] {f[0], f[1], f[2], f[3], f[4]});
    }
  }

/*
 sample:
Printer1 is ready and printing
Rank    Owner   Job     File(s)                         Total Size
active  (null)  1       untitled                        43008 bytes
1st     (null)  2       untitled                        0 bytes
 sample:
Printer1 is ready
no entries
 sample:
lpq: Unknown destination "test".
*/

  private void deleteJob() {
    int row = jobs.getSelectedRow();
    if (row == -1) return;
    String jobId = (String)jobs.getValueAt(row, 2);
    ShellProcess sp = new ShellProcess();
    String output = sp.run(new String[] {"lprm", "-P", pname, jobId}, false);
  }

  private void setPosition() {
    Rectangle s = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
    Dimension d = getSize();
    setLocation(s.width/2 - d.width/2, s.height/2 - (d.height/2));
  }
}
